/*
 * WorstFit.cpp
 *
 *  Created on: 04.03.2011
 *      Author: marco
 */

#include "WorstFit.h"
#include "WorstFitArea.h"
#include "Area.h"
#include <assert.h>

//WorstFit::WorstFit() {
//	//memory = new WorstFitArea(hole, 0, )
//}

void WorstFit::free(const Area* area) {
	Area* a = (Area*)area;
	if (WorstFitArea* wfarea = dynamic_cast<WorstFitArea*>(a)) {
		wfarea->free();
	}
}

const Area * WorstFit::alloc(int process_size){
	assert(process_size < size);
	assert(process_size > 0);

	WorstFitArea* area = memory;
	WorstFitArea* biggest = 0;

//	bool first = false;
//	do {
//		if (!first)
//			area = area->getNext();
//		first=false;
//		if (area->getType() == hole) {
//			if (biggest==0 || area->getSize() > biggest->getSize())
//				biggest = area;
//		}
//	} while (area->hasNext());

	while (area != 0) {
		if (area->getType() == hole) {
			if (biggest==0 || area->getSize() > biggest->getSize())
				biggest = area;
		}
		area = area->getNext();
	}
	if (biggest == 0)
		biggest = memory;
	if (biggest->getSize() >= process_size)
		return biggest->allocate(process_size);
	else
		return 0;
}

void WorstFit::setSize(int size) {
	Allocator::setSize(size);
	memory = new WorstFitArea(hole, 0, size, 0,0);
}

WorstFit::~WorstFit() {

}
